package com.guet.service.impl;

import com.guet.VO.PaperVO;
import com.guet.VO.StatisticsCountVO;
import com.guet.VO.StatisticsVO;
import com.guet.context.BaseContext;
import com.guet.mapper.StatisticsMapper;
import com.guet.service.StatisticsService;
import com.guet.service.TestService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class StatisticsServiceImpl implements StatisticsService {

    @Autowired
    private StatisticsMapper statisticsMapper;
    @Autowired
    private TestService testService;


    /**
     * 根据paperId查询分数
     *
     * @param paperId
     * @return
     */
    @Override
    public List<StatisticsVO> list(int paperId) {
        return statisticsMapper.list(paperId);
    }

    /**
     * 获取不同分数段的学生数量
     *
     * @param paperId
     * @return
     */
    @Override
    public List<Integer> getScoreDistribution(int paperId) {
        Long userId = BaseContext.getCurrentId();
        List<Integer> personsCount = new ArrayList<>();

        // 构建查询参数
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("paperId", paperId);

        // 定义分数区间
        int[][] scoreRanges = {
                {90, 101},
                {80, 90},
                {70, 80},
                {60, 70},
                {0, 60}
        };

        // 遍历分数区间计算人数
        for (int[] range : scoreRanges) {
            queryParams.put("scoreLow", range[0]);
            queryParams.put("scoreHigh", range[1]);

            // 查询当前分数区间的人数
            Integer count = statisticsMapper.countPerson(queryParams);
            personsCount.add(count);
        }
        return personsCount;
    }

    @Override
    public void exportScoreData(HttpServletResponse response, int id) {
        List<StatisticsVO> statisticsVOList = statisticsMapper.list(id);
        PaperVO paper = testService.getPaperById(id);
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/template.xlsx");

        try {
            if (in == null) {
                return;
            }

            // 创建工作簿和工作表
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("sheet1");

            // 填充试卷名称和其他内容
            XSSFRow row = sheet.getRow(2);
            row.getCell(1).setCellValue(paper.getTitle());
            row = sheet.getRow(3);
            row.getCell(1).setCellValue(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

            // 填充学生成绩数据
            for (int i = 0; i < statisticsVOList.size(); i++) {
                StatisticsVO statisticsVO = statisticsVOList.get(i);
                row = sheet.getRow(5 + i);
                row.getCell(0).setCellValue(statisticsVO.getStuId());
                row.getCell(1).setCellValue(statisticsVO.getUsername());
                row.getCell(2).setCellValue(statisticsVO.getScore());
            }

            // 确保保存文件的目录存在，如果不存在则创建
            File dir = new File("D:/score_result");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 设置文件保存路径
            // 清理文件名中的非法字符
            String fileName = paper.getTitle().replaceAll("[<>:\"/\\|?*]", "_"); // 替换非法字符为下划线
            fileName = fileName.length() > 100 ? fileName.substring(0, 100) : fileName; // 限制文件名长度

// 构建文件路径
            String filePath = "D:/score_result/学生成绩_" + fileName + ".xlsx";


            // 使用 FileOutputStream 将文件保存到磁盘
            FileOutputStream fileOut = new FileOutputStream(filePath);

            // 将 Excel 内容写入文件
            excel.write(fileOut);

            // 关闭资源
            fileOut.close();
            excel.close();

            // 日志打印保存路径
            log.info("文件已成功保存到: {}", filePath);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 每个模块的内容数量
     * @return
     */
    @Override
    public StatisticsCountVO getStatisticsCount() {
        return statisticsMapper.getStatisticsCount();
    }


}
